/**
 * PHOSIDE: PHosphorylation Site IDentification Engine.
 * Copyright 2009 Digital Biology Lab, University of Missouri.
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version. <p/> This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more
 * details.
 */

package phoside.miscellaneous.io;

import java.io.InputStream;
import java.io.IOException;

import java.util.Iterator;
import java.util.List;

import phoside.PhosphoProteins;
import phoside.Protein;

import phoside.classify.result.PhosidePredictionResult;
import phoside.classify.result.PhosidePredictionResultImpl;

import phoside.io.ProteinsReader;
import phoside.io.xml.PhosideXmlProteinsReader;
import phoside.io.xml.PhosphoProteinFieldValueFormatter;

import phoside.util.IOUtil;
import phoside.util.ClientHttpRequest;

/**
 *
 * @author gjj
 */
public class PhosphoReaderScanSite implements ProteinsReader {
    private PhosidePredictionResult data;
    private String dirReport;
    private String kinase;

    public PhosphoReaderScanSite(PhosidePredictionResult data,
            String dirReport, String kinase) {
        this.data = data;
        this.dirReport = dirReport;
        this.kinase = kinase;
    }

    public PhosphoProteins read() throws IOException {
        List<String> files = IOUtil.listFilesInFolder(dirReport);
        
        String lineOfKinaseStarts = "<tr><td colspan=3 align=center " +
                "bgcolor=blue><font color=white><b>"+kinase+"</b>";

        for (String file : files) {
            String acc = file.substring(0, file.indexOf(".html"));
            System.out.print(acc);
            List<String> lines = IOUtil.readStringListAscii(dirReport+java.io.File.separator+file);
            int nline = lines.size();
            int iline = 0;
            while (iline<nline) {
                String line = lines.get(iline);
                if (line.startsWith(lineOfKinaseStarts)) {
                    iline += 2;
                    line = lines.get(iline);
                    String strsite = line.substring(9);
                    int idx = strsite.indexOf("</td><td>");
                    strsite = strsite.substring(0, idx);
                    int site = Integer.parseInt(strsite)-1;
                    try {
                        data.addSite(acc, site);
                    } catch (IllegalStateException e) {
                        System.err.print(e.getMessage());
                        continue;
                    }
                    System.out.print("\t"+site);
                }
                iline++;
            }
            System.out.println();
        }

        return data;
    }

    public void saveResult(String dirSave) throws IOException {
        //FileWriter fout = new FileWriter(dirSave);
        //BufferedWriter out = new BufferedWriter(fout);

        Iterator<Protein> it = data.proteinIterator();
        while (it.hasNext()) {
            Protein protein = it.next();
            String acc = protein.getAccession();

            //if (!acc.startsWith("EN")) continue;

            //out.write(">"+acc);
            //out.newLine();

            try {
//                InputStream is = ClientHttpRequest.post(
//                                  new java.net.URL("http://scansite.mit.edu/cgi-bin/motifscan_id"),
//                                  new Object[] {
//                                                "protein_id", acc,
//                                                "database", acc.startsWith("EN")?"ensembl":"swissprot",
//                                                "motif_option", "all",
//                                                "stringency", "Medium"
//                                               });
                InputStream is = ClientHttpRequest.post(
                                  new java.net.URL("http://scansite.mit.edu/cgi-bin/motifscan_seq"),
                                  new Object[] {
                                                "protein_id", acc,
                                                "sequence", protein.getSequence(),
                                                "motif_option", "all",
                                                "stringency", "High"
                                               });

                java.util.List<String> lines = IOUtil.readStringListAscii(new java.io.InputStreamReader(is));

                IOUtil.writeCollectionAscii(lines, dirSave+java.io.File.separator+acc+".html");
//                for (String line:lines) {
//                    out.write(line);
//                    out.newLine();
//                }
//
//                out.newLine();

            } catch (Exception e) {
                System.err.println("\t"+acc);
                e.printStackTrace();
                continue;
            }

            System.out.println(acc);
//            break;

        }

//        out.close();
//        fout.close();
    }

    public static void main(String[] args) {
        String testXml = "data\\phosphoelm\\Human-UniProt-SwissProt-V15.8-20090922-PhosphoELM-V8.2-April2009-nr50";
        //String testXml = "exp\\test1\\kinase-specific\\Human-UniProt-SwissProt-V15.8-20090922-PhosphoELM-V8.2-April2009-nr50-nonphosphoonly-random200";
        PhosidePredictionResult data = new PhosidePredictionResultImpl(null);
        PhosideXmlProteinsReader readerxml = new PhosideXmlProteinsReader(testXml+".xml", data,
                new PhosphoProteinFieldValueFormatter());

        String kinase = "Casein Kinase 2";
        PhosphoReaderScanSite reader = new PhosphoReaderScanSite(data,testXml+".raw.scansite.high",kinase);

        phoside.io.xml.PhosideXmlProteinsWriter writer
                = new phoside.io.xml.PhosideXmlProteinsWriter(testXml+".scansite.high.CK2.xml",
                  new phoside.io.xml.PhosphoProteinFieldValueFormatter());

        try {
            readerxml.read();
            for (String acc : data.getProteinsAccessions()) {
                data.clearSites(acc);
                data.getProtein(acc).removeInfo(phoside.util.StaticFinalValues.DISORDER);
            }

//            reader.saveResult(testXml+".raw.scansite.medium");

            reader.read();

            writer.write(data);
        } catch(IOException e) {
            e.printStackTrace();
        }

    }
}
